package com.tanhua.dubbo.server.api;

import cn.hutool.core.convert.Convert;
import com.alibaba.dubbo.config.annotation.Service;
import com.tanhua.dubbo.server.pojo.UserLogin;
import com.tanhua.dubbo.server.vo.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;

import java.util.List;

@Service(version = "1.0.0")
public class logApiImpl implements LogApi {
    @Autowired
    private MongoTemplate mongoTemplate;

    @Override
    public PageInfo<UserLogin> findLogRecord(Integer page, Integer pageSize, String sortProp, String sortOrder, Integer type, Long uid) {
         PageRequest pageRequest =null;

        //升序排序
         if(sortOrder.equals("ascending")) {
             pageRequest = PageRequest.of(page - 1, pageSize, Sort.by(Sort.Order.asc("logTime")));
         }else {
             //降序排序
             pageRequest =PageRequest.of(page-1,pageSize,Sort.by(Sort.Order.desc("logTime")));
         }
        //查询用户登录的所有日志信息
        Query query=Query.query(Criteria.where("userId").is(uid)).with(pageRequest);
        List<UserLogin> userLogins = mongoTemplate.find(query, UserLogin.class);
         //统计用户登录的日志信息总数量
        Query query1 = Query.query(Criteria.where("userId").is(uid));
        long count = mongoTemplate.count(query1, UserLogin.class);
        //封装pageInfo
        PageInfo<UserLogin> pageInfo = new PageInfo();
        pageInfo.setPageNum(page);//当前页
        pageInfo.setPageSize(pageSize);//每页显示条数
        pageInfo.setRecords(userLogins);
        pageInfo.setTotal(Convert.toInt(count));
        return pageInfo;
    }
}
